import torch  
import torch.nn as nn 

X = torch.tensor([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0]).view(-1,1)  # 定义输入数据X，改变结构为了之后前向传播使用
y = torch.tensor([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0]).view(-1,1)  # 定义真实标签y，改变结构为了之后前向传播使用

#定义单程感知机
class Perceptron(nn.Module):
    def __init__(self):
        super().__init__() 
        self.fc = nn.Linear(1,1)

    def forward(self, x):      
        y = self.fc.forward(x)
        return y
  
model = Perceptron()
print("已经创建模型:", model) 
if model.training == True:
    print("模型当前(默认)处于训练模式")

loss_fnc = nn.MSELoss(reduction='mean')  # 定义损失函数为均方误差
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # 定义优化器为随机梯度下降, 学习率为0.01

# 循环500次，每次都进行一次训练
for epoch in range(500):
    y_pred = model.forward(X)
    loss = loss_fnc(y_pred, y)    
    optimizer.zero_grad()   
    loss.backward()
    optimizer.step()
    if (epoch+1) % 50 == 0:
        print(f'Epoch [{epoch+1}/500], Loss: {loss.item():.4f}')

model.eval() # 将模型调整为评估模式
if model.training == False:
    print("模型当前处于评估模式")
with torch.no_grad():
    x_test = torch.tensor([10.0])
    y_test = model.forward(x_test.unsqueeze(0))
    print(f'测试输入x: {x_test.item()}')  
    print(f'测试输出y: {y_test.item()}')